<template>
  <div class="chart-container" :style="{ width: containerWidth }">
    <!-- 美观的图表容器 -->
    <div ref="chartContainer" class="chart-wrapper"></div>

    <!-- 美化的标题 -->
    <div class="chart-title">
      <h3>{{ title }}</h3>
      <div class="data-indicator">
        <span class="width-indicator">宽度: {{ Math.round(parseFloat(containerWidth)) }}%</span>
        <span class="data-count">{{ data.length }} 项数据</span>
        <div class="status-dot" :class="{ 'active': !loading }"></div>
      </div>
    </div>

    <!-- 拖拽调整器 -->
    <div class="width-resizer" @mousedown="startResize" @dblclick="resetToFullWidth">
      <div class="resizer-handle">
        <div class="resizer-line"></div>
        <div class="resizer-line"></div>
        <div class="resizer-line"></div>
      </div>
    </div>

    <!-- 加载动画 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-animation">
        <div class="wave"></div>
        <div class="wave"></div>
        <div class="wave"></div>
      </div>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import type { AdData } from '../types/ad'

const props = defineProps<{
  title: string
  data: AdData[]
  loading?: boolean
}>()

const chartContainer = ref<HTMLDivElement | null>(null)
let chartInstance: echarts.ECharts | null = null
const containerWidth = ref('100%')
const isResizing = ref(false)

const startResize = (event: MouseEvent) => {
  isResizing.value = true
  const startX = event.clientX
  const startWidth = parseFloat(containerWidth.value)

  const handleMouseMove = (e: MouseEvent) => {
    if (!isResizing.value) return

    const deltaX = e.clientX - startX
    const parentWidth = (event.target as HTMLElement).closest('.charts')?.clientWidth || 800
    const widthChange = (deltaX / parentWidth) * 100

    // 限制宽度在30% - 150%之间
    const newWidth = Math.max(30, Math.min(150, startWidth + widthChange))
    containerWidth.value = `${newWidth}%`

    // 实时调整图表大小
    if (chartInstance) {
      requestAnimationFrame(() => {
        chartInstance?.resize()
      })
    }
  }

  const handleMouseUp = () => {
    isResizing.value = false
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
  }

  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)

  event.preventDefault()
}

const resetToFullWidth = () => {
  containerWidth.value = '100%'
  setTimeout(() => {
    if (chartInstance) {
      chartInstance.resize()
    }
  }, 300)
}

const initChart = () => {
  if (!chartContainer.value) return

  // 销毁已存在的实例
  if (chartInstance) {
    chartInstance.dispose()
  }

  // 创建新实例
  chartInstance = echarts.init(chartContainer.value)

  updateChart()

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize()
    }
  })
}

const updateChart = () => {
  if (!chartInstance) return

  const hasData = props.data && props.data.length > 0

  const option = {
    backgroundColor: 'transparent',
    title: {
      show: false // 使用自定义标题
    },
    grid: {
      top: 40,
      left: 70,
      right: 30,
      bottom: 70
    },
    xAxis: {
      type: 'category',
      data: hasData ? props.data.map(item => item.date) : ['示例1', '示例2', '示例3'],
      axisLine: {
        lineStyle: {
          color: '#e2e8f0'
        }
      },
      axisLabel: {
        color: '#64748b',
        fontSize: 11,
        margin: 15,
        rotate: 45, // 旋转标签避免重叠
        interval: 'auto', // 自动间隔显示
        formatter: function (value: string) {
          // 简化日期显示，只在月初显示月份
          if (value.includes('1日') || value.includes('15日')) {
            return value;
          }
          return value.replace('月', '/').replace('日', '');
        }
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#f1f5f9',
          type: 'dashed'
        }
      },
      axisLabel: {
        color: '#64748b',
        fontSize: 12,
        margin: 15
      }
    },
    series: [{
      name: props.title,
      data: hasData ? props.data.map(item => item.value) : [120, 200, 150],
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        width: 2,
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 1,
          y2: 0,
          colorStops: [{
            offset: 0,
            color: '#3b82f6'
          }, {
            offset: 1,
            color: '#8b5cf6'
          }]
        }
      },
      itemStyle: {
        color: '#3b82f6',
        borderColor: '#fff',
        borderWidth: 1
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(59, 130, 246, 0.2)'
          }, {
            offset: 1,
            color: 'rgba(59, 130, 246, 0.02)'
          }]
        }
      },
      animation: true,
      animationDuration: 2000,
      animationEasing: 'cubicInOut'
    }],
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#e2e8f0',
      borderWidth: 1,
      textStyle: {
        color: '#1e293b'
      },
      axisPointer: {
        type: 'cross',
        lineStyle: {
          color: '#3b82f6',
          width: 1,
          type: 'dashed'
        }
      },
      formatter: function (params: any) {
        const data = params[0];
        return `<div style="padding: 8px;">
          <div style="font-weight: bold; margin-bottom: 4px;">${data.seriesName}</div>
          <div>日期: ${data.name}</div>
          <div>数值: ${data.value.toLocaleString()}</div>
        </div>`;
      }
    },
    dataZoom: [
      {
        type: 'slider',
        show: hasData && props.data.length > 30,
        xAxisIndex: 0,
        start: 0,
        end: 100,
        height: 20,
        bottom: 10,
        borderColor: '#e2e8f0',
        fillerColor: 'rgba(59, 130, 246, 0.1)',
        handleStyle: {
          color: '#3b82f6'
        }
      }
    ]
  }

  chartInstance.setOption(option)
}

onMounted(() => {
  nextTick(() => {
    setTimeout(() => {
      initChart()
    }, 100)
  })
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }

  window.removeEventListener('resize', () => { })
})

watch(() => props.data, () => {
  updateChart()
}, { deep: true })

watch(containerWidth, () => {
  nextTick(() => {
    if (chartInstance) {
      setTimeout(() => {
        chartInstance?.resize()
      }, 100)
    }
  })
})
</script>

<style scoped>
.chart-container {
  position: relative;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  border-radius: 20px;
  box-shadow:
    0 8px 20px -4px rgba(0, 0, 0, 0.12),
    0 4px 10px -2px rgba(0, 0, 0, 0.08);
  padding: 20px;
  margin: 8px 0;
  transition: all 0.3s cubic-bezier(0.4, 0.0, 0.2, 1);
  animation: slideInUp 0.6s ease-out;
  border: 1px solid rgba(226, 232, 240, 0.8);
  backdrop-filter: blur(10px);
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: visible;
  width: 100%;
  min-width: 300px;
}

.chart-container::before {
  content: '双击重置宽度';
  position: absolute;
  top: 8px;
  right: 15px;
  font-size: 10px;
  color: rgba(100, 116, 139, 0.5);
  pointer-events: none;
  transition: opacity 0.3s ease;
  z-index: 10;
  opacity: 0;
}

.chart-container:hover::before {
  opacity: 1;
}

.chart-container:hover {
  transform: translateY(-4px);
  box-shadow:
    0 20px 35px -6px rgba(0, 0, 0, 0.12),
    0 12px 18px -4px rgba(0, 0, 0, 0.08);
  border-color: rgba(59, 130, 246, 0.4);
}

.chart-wrapper {
  height: 500px;
  width: 100%;
  position: relative;
  border-radius: 16px;
  overflow: hidden;
  transition: all 0.3s ease;
  flex: 1;
}

.chart-wrapper:hover {
  box-shadow: inset 0 0 20px rgba(59, 130, 246, 0.1);
}

.chart-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 12px;
  border-bottom: 2px solid rgba(59, 130, 246, 0.2);
  flex-shrink: 0;
}

.chart-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
  color: #1e293b;
  background: linear-gradient(135deg, #3b82f6, #8b5cf6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  letter-spacing: -0.5px;
}

.data-indicator {
  display: flex;
  align-items: center;
  gap: 12px;
}

.width-indicator {
  font-size: 12px;
  font-weight: 500;
  color: #3b82f6;
  background: rgba(59, 130, 246, 0.1);
  padding: 4px 8px;
  border-radius: 12px;
  transition: all 0.3s ease;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.data-count {
  font-size: 13px;
  font-weight: 500;
  color: #64748b;
  background: rgba(59, 130, 246, 0.1);
  padding: 6px 12px;
  border-radius: 16px;
  transition: all 0.3s ease;
}

.status-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #94a3b8;
  transition: all 0.3s ease;
}

.status-dot.active {
  background: #22c55e;
  box-shadow: 0 0 8px rgba(34, 197, 94, 0.4);
  animation: pulse 2s infinite;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(4px);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 16px;
  z-index: 10;
}

.loading-animation {
  display: flex;
  gap: 4px;
  margin-bottom: 16px;
}

.wave {
  width: 8px;
  height: 40px;
  background: linear-gradient(135deg, #3b82f6, #8b5cf6);
  border-radius: 4px;
  animation: wave 1.2s ease-in-out infinite;
}

.wave:nth-child(2) {
  animation-delay: 0.2s;
}

.wave:nth-child(3) {
  animation-delay: 0.4s;
}

.loading-overlay p {
  color: #64748b;
  font-size: 14px;
  margin: 0;
}

/* 动画定义 */
@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(24px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {

  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0.5;
  }
}

@keyframes wave {

  0%,
  100% {
    transform: scaleY(1);
  }

  50% {
    transform: scaleY(0.3);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-container {
    margin: 5px 0;
    padding: 15px;
    border-radius: 16px;
  }

  .chart-wrapper {
    height: 350px;
  }

  .chart-title h3 {
    font-size: 16px;
  }

  .chart-title {
    margin-bottom: 12px;
    padding-bottom: 10px;
  }
}

@media (min-width: 1200px) {
  .chart-wrapper {
    height: 550px;
  }

  .chart-container {
    padding: 25px;
    border-radius: 24px;
  }

  .chart-title h3 {
    font-size: 20px;
  }
}

.width-resizer {
  position: absolute;
  top: 50%;
  right: -10px;
  transform: translateY(-50%);
  width: 20px;
  height: 60px;
  cursor: ew-resize;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.width-resizer:hover {
  right: -12px;
}

.resizer-handle {
  width: 8px;
  height: 40px;
  background: linear-gradient(135deg, #3b82f6, #8b5cf6);
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 2px;
  box-shadow:
    0 4px 8px rgba(0, 0, 0, 0.1),
    0 2px 4px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  position: relative;
}

.resizer-handle:hover {
  background: linear-gradient(135deg, #2563eb, #7c3aed);
  box-shadow:
    0 6px 12px rgba(0, 0, 0, 0.15),
    0 3px 6px rgba(0, 0, 0, 0.1);
  transform: scale(1.1);
}

.resizer-handle::before {
  content: '↔';
  position: absolute;
  top: -25px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 10px;
  color: #64748b;
  background: rgba(255, 255, 255, 0.9);
  padding: 2px 4px;
  border-radius: 4px;
  opacity: 0;
  transition: opacity 0.3s ease;
  font-weight: bold;
}

.width-resizer:hover .resizer-handle::before {
  opacity: 1;
}

.resizer-line {
  width: 2px;
  height: 4px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 1px;
}
</style>